import React, { useEffect, useState, useCallback } from 'react';
import { useLocation, useHistory } from 'react-router-dom';
import { ImagePicker, WhiteSpace, Toast, Modal } from 'antd-mobile';
import { getDetail, getImage, uploadImage, deleteImage } from '../../services/Handle';
import List from "antd-mobile/es/list";
import {Brief} from "antd-mobile/es/list/ListItem";
import {logout} from "../../services/Login";
import useUserInfo from "../../models/userInfo";

function useQuery() {
  return new URLSearchParams(useLocation().search);
}

const Index = () => {
  const [state, setState] = useState({
    time: '2020-20-20 11:11:11',
    name: 'test_name',
    single: true,
    list: [],
  });
  const query = useQuery();
  const { userInfo, saveUserInfo } = useUserInfo();
  const history = useHistory();

  useEffect(() => {
    const fetch = async () => {
      Toast.loading('加载中...');
      const promiseArray = [
        getDetail(parseInt(query.get('id'), 10)),
        getImage(parseInt(query.get('id'), 10)),
      ];

      const [detail, image] = await Promise.all(promiseArray);

      const temp = detail.data[0].expiration.split('T');

      setState((s) => ({
        ...s,
        single: detail.data[0].single,
        time: `${temp[0]} ${temp[1].split('+')[0]}`,
        name: detail.data[0].name,
        list: image.data,
      }));

      Toast.hide();
    };

    fetch();
  }, []);

  const imageChange = useCallback(
    async (images, option, index) => {
      Toast.loading('上传中...');
      try {
        if (option === 'add') {
          await uploadImage(images[0].file, parseInt(query.get('id'), 10));
          const imageList = await getImage(parseInt(query.get('id'), 10));

          setState((s) => ({
            ...s,
            list: [...imageList.data],
          }));
        }

        // if (option === 'remove') {
        //   await deleteImage(state.list[index].place);
        //   setState((s) => ({
        //     ...s,
        //     list: s.list.splice(index, 1),
        //   }));
        // }

        Toast.hide();
      } catch (e) {
        Toast.hide();
        Toast.fail(e.message);
      }
    },
    [state.list],
  );

  const onDeleteImage = async (index) => {
      await deleteImage(state.list[index].place);
      setState((s) => ({
        ...s,
        list: [...s.list.splice(index, 1)],
      }));
  };

  const onLogout = async () => {
    await logout();
    saveUserInfo(null, null, null);
    history.push('/login');
  };

  const authSecretKey = async () => {
    Modal.prompt('需要验证该作业的 s-key', '',
      [
        {
          text: '取消',
        }, {
          text: '确认并进入',
          onPress: value => history.push(`/result?id=${query.get('id')}&secretkey=${value}`),
        },
      ], 'default', null, ['s-key']);
  };

  return (
    <div>
      <div style={{display: 'flex', justifyContent: 'space-between'}}>
        <div>当前用户：{userInfo.nk}</div>
        <div onClick={() => onLogout()}>登出</div>
      </div>
      <WhiteSpace />
      <div style={{ fontSize: '1.4rem' }}>{state.name}</div>
      <div>截止时间：{state.time}</div>
      <div onClick={() => authSecretKey()} style={{ paddingTop: '0.7rem', color: 'rgba(0,0,0,0.4)', fontSize: '0.7rem' }}>点此进入作业提交统计页</div>
      <WhiteSpace />
      <List renderHeader='已上交的作业'>
        {
          state.list.length > 0 ? state.list.map((item, index) => (
              <List.Item>
                <div style={{textAlign: 'center'}}>{item.name}</div>
                <div style={{textAlign: 'center', fontSize: '0.9rem', color: 'rgba(72,72,255,0.8)'}} onClick={() => onDeleteImage(index)}>删除</div>
                <img src={item.url} style={{marginTop: '10px', width: '100%', height: '100%'}}/>
              </List.Item>
          )) : <List.Item><Brief>无</Brief></List.Item>
        }
      </List>
      <ImagePicker
        files={[]}
        onChange={imageChange}
        selectable={
          (state.single && state.list.length < 1) || (!state.single && state.list.length < 5)
        }
        accept="image/*"
      />
    </div>
  );
};

export default Index;
